import { ElButton, ElCol, ElImage, ElLink, ElMessage, ElRow } from 'element-plus'
import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import IconOpenTime from '@/assets/customer/opentime.png'
import toNative from '@/utils/toNative'
import renderModal, {
    getModelValue,
    initModelValue,
    type FormModalDto
} from '@/components/modal/Modal'
import { editPeriodStatus, getTomorrowEnsureCost } from '@/api/customer'
import { useBasicStore } from '@/stores/basic'
import { DeviceEnum } from '@/const/enum'
import type { CompanyInfoDto, PeriodInfoDto } from '@/api/company/types'
import { periodWithdrawAccountBlance } from '@/api/company'
import DialogClaimRate from './DialogClaimRate'

import { getPeriodInfo, updatePeriodOverdraftAmount } from '@/api/insurance/period'
import DialogOverAge from './DialogOverAge'
import type { JSX } from 'vue/jsx-runtime'
import DrawerInsurancePlan from './DrawerInsurancePlan'
import type { PeriodDataDto } from '@/api/insurance/period/types'
import DrawerOperateRecord from './DrawerOperateRecord'

import RenderDescription, { type DescItemDto } from '@/components/render-descriotion/Index'
import { updateRebateStatus } from '@/api/insurance/company'

type FormDialogType =
    | 'withdrawFormConfig'
    | 'rebateFormConfig'
    | 'overDraftFormConfig'
    | 'accountSettingFormConfig'
type OpenShowType = 'showClaimRate' | 'showOverAge' | 'showInsurancePlan' | 'showOperatorRecord'
@Component
export class BasicInfoView extends Render {
    @Prop() basicData!: PeriodInfoDto
    @Prop() companyBasicInfo!: CompanyInfoDto

    @Emit('refresh')
    handleRefresh() {}

    @Watch('basicData', { immediate: true })
    handleWatchBasicData() {
        this.basicData?.companyId && this.getPeriodData()
    }

    basicStore = useBasicStore()

    showClaimRate = false
    showOverAge = false
    tomorrowCoast = 0

    showInsurancePlan = false
    showOperatorRecord = false

    periodData = {} as PeriodDataDto

    get basicInfoData() {
        return [
            {
                label: '所属销售',
                value: this.basicData.salesName
            },
            {
                label: '账户余额',
                value: this.basicData.wesureBalance,
                suffix: '￥',
                buttonName: '提现',
                callback: this.onWithdraw
            },
            {
                label: '理赔率',
                value: this.basicData.claimRate,
                buttonName: '查看',
                callback: () => {
                    this.onShow('showClaimRate')
                }
            },
            {
                label: '总充值保费',
                value: this.basicData.totalRechargeAmount,
                prefix: '￥'
            },
            {
                label: '返利状态',
                value: this.basicData.openRebate === 0 ? '未返利' : '返利中',
                buttonName: '设置',
                callback: () => {
                    this.onShowFormDialog('rebateFormConfig')
                }
            },
            {
                label: '可欠费额度',
                value: this.basicData.periodOverdraftAmount || '--',
                callback: () => this.onShowFormDialog('overDraftFormConfig')
            }
        ] as DescItemDto[]
    }

    // 账户余额提现
    withdrawFormConfig = this.initWithdrawFormConfig() as FormModalDto
    initWithdrawFormConfig() {
        return {
            title: '',
            width: '450px',
            theme: 'light',
            show: false,
            items: {
                withdrawAmount: {
                    name: '提现金额',
                    element: 'inputNumber',
                    required: true,
                    params: {
                        min: 0,
                        after: (
                            <ElLink underline={false} type="primary" onClick={this.onWithdrawAll}>
                                全部提现
                            </ElLink>
                        )
                    }
                },
                hint1: {
                    name: '',
                    element: 'text',
                    value: ''
                },
                hint2: {
                    name: '',
                    element: 'text',
                    value: ''
                },
                remark: {
                    name: '备注',
                    element: 'textarea'
                }
            },
            complete: async () => {
                const data = getModelValue(this.withdrawFormConfig)
                data.companyId = this.basicData.companyId

                delete data.hint1
                delete data.hint2

                await periodWithdrawAccountBlance(data)

                ElMessage.success('提现成功')
                this.handleRefresh()
                this.withdrawFormConfig.show = false
            },
            cancel: () => {
                this.withdrawFormConfig.show = false
            },
            init: async () => {
                this.withdrawFormConfig.items.hint1.value = `账户余额：￥${this.basicData.wesureBalance ?? 0}`
                this.withdrawFormConfig.items.hint2.value = `明日保费需扣金额：￥${this.tomorrowCoast ?? 0}`
                this.withdrawFormConfig.items.withdrawAmount.params.max =
                    this.basicData.wesureBalance
            }
        } as FormModalDto
    }

    // 返利设置
    rebateFormConfig = this.initRebateFormConfig() as FormModalDto
    initRebateFormConfig() {
        return {
            title: '返利设置',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                openRebate: {
                    name: '是否允许返利',
                    element: 'switch',
                    required: true,
                    params: { activeValue: 1, inactiveValue: 0 }
                }
            },
            complete: async () => {
                const data = getModelValue(this.rebateFormConfig)
                data.companyId = this.basicData.companyId
                await updateRebateStatus(data)
                ElMessage.success('设置成功')
                this.handleRefresh()
                this.rebateFormConfig.show = false
            },
            cancel: () => {
                this.rebateFormConfig.show = false
            },
            init: async () => {
                initModelValue(this.rebateFormConfig, this.basicData)
            }
        } as FormModalDto
    }

    // 可欠费额度
    overDraftFormConfig = this.initOverdraftFormConfig() as FormModalDto
    initOverdraftFormConfig() {
        return {
            title: '可欠费额度设置',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                periodOverdraftAmount: {
                    name: '可欠费额度',
                    element: 'inputNumber',
                    required: true,
                    params: {
                        precision: 2,
                        min: 0
                    }
                }
            },
            complete: async () => {
                const data = getModelValue(this.overDraftFormConfig)
                data.companyId = this.basicData.companyId
                await updatePeriodOverdraftAmount(data)
                ElMessage.success('操作成功')
                this.handleRefresh()
                this.overDraftFormConfig.show = false
            },
            cancel: () => {
                this.overDraftFormConfig.show = false
            },
            init: async () => {}
        } as FormModalDto
    }

    // 账户设置
    accountSettingFormConfig = this.initAccountSettingFormConfig() as FormModalDto
    initAccountSettingFormConfig() {
        return {
            title: '账户设置',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                refusalGuaranteeStatus: {
                    name: '拒保',
                    element: 'switch',
                    required: true,
                    params: { activeValue: 1, inactiveValue: 0 }
                }
            },
            complete: async () => {
                const data = getModelValue(this.accountSettingFormConfig)
                data.companyId = this.basicData.companyId
                data.userType = 2
                await editPeriodStatus(data)
                ElMessage.success('操作成功')
                this.handleRefresh()
                this.accountSettingFormConfig.show = false
            },
            cancel: () => {
                this.accountSettingFormConfig.show = false
            },
            init: async () => {
                initModelValue(this.accountSettingFormConfig, this.basicData)
            }
        } as FormModalDto
    }

    async getPeriodData() {
        const res = await getPeriodInfo({ companyId: this.basicData.companyId })
        this.periodData = res
    }

    async getTomorrowCoast() {
        const res = await getTomorrowEnsureCost({ companyId: this.basicData.companyId })
        return res
    }

    async onWithdraw() {
        await this.getTomorrowCoast()
        this.withdrawFormConfig.show = true
        this.withdrawFormConfig.title = `${this.companyBasicInfo.companyName}账户提现`
    }

    onWithdrawAll() {
        this.withdrawFormConfig.items.withdrawAmount.value = this.basicData.wesureBalance
    }

    onShowFormDialog(type: FormDialogType) {
        this[type].show = true
    }

    onShow(type: OpenShowType) {
        this[type] = true
    }

    renderCard(name: string, fnView: () => void, element: JSX.Element) {
        return (
            <ElCol xl={8} lg={8} md={8} sm={24} xs={24}>
                <div class="border border-solid rounded-lg p-16px flex-1">
                    <div class="flex items-center justify-between mb-20px">
                        <div>{name}</div>
                        <div
                            class="text-blue-default text-sm cursor-pointer"
                            onClick={() => fnView()}
                        >
                            查看
                        </div>
                    </div>
                    {element}
                </div>
            </ElCol>
        )
    }

    renderCardItem(name: string, value: number | string) {
        return (
            <div class="flex-1">
                <div class="text-sm text-gray-default mb-20px">{name}</div>
                <div class="font-bold text-26px">{value}</div>
            </div>
        )
    }

    render() {
        return (
            <div>
                <div class="bg-white-dark-100 text-base px-12px py-8px">基本信息</div>
                <div class="flex my-12px flex-wrap">
                    <div class="flex items-center">
                        <ElImage class="w-16px h-16px mr-6px" src={IconOpenTime}></ElImage>
                        <div>开通时间：{this.basicData.productOpenTime}</div>
                    </div>
                </div>
                <RenderDescription renderData={this.basicInfoData} />
                <div class="my-20px">
                    <ElButton
                        plain
                        size="small"
                        onClick={() => this.onShowFormDialog('accountSettingFormConfig')}
                    >
                        账户设置
                    </ElButton>
                    <ElButton plain size="small" onClick={() => this.onShow('showOverAge')}>
                        超龄限制
                    </ElButton>
                </div>
                {/* 账户提现 */}
                {renderModal(this.withdrawFormConfig)}
                {/* 返利设置 */}
                {renderModal(this.rebateFormConfig)}
                {/* 可欠费额度 */}
                {renderModal(this.overDraftFormConfig)}
                {/* 账户设置 */}
                {renderModal(this.accountSettingFormConfig)}
                {/* 理赔率 */}
                <DialogClaimRate
                    v-model:show={this.showClaimRate}
                    companyId={this.companyBasicInfo.companyId}
                    companyName={this.companyBasicInfo.companyName}
                />
                {/* 超龄投保设置 */}
                <DialogOverAge
                    v-model:show={this.showOverAge}
                    companyId={this.companyBasicInfo.companyId}
                />

                <ElRow gutter={20}>
                    {this.renderCard(
                        '保险方案',
                        () => this.onShow('showInsurancePlan'),
                        <div class="flex">
                            {this.renderCardItem('未失效', this.periodData.unexpiredPlanCount)}
                            {this.renderCardItem('已失效', this.periodData.expirePlanCount)}
                        </div>
                    )}
                    {this.renderCard(
                        '加减保记录',
                        () => this.onShow('showOperatorRecord'),
                        <div class="flex">
                            {this.renderCardItem('加保(次)', this.periodData.addInsur)}
                            {this.renderCardItem('减保(次)', this.periodData.reduceInsur)}
                            {this.renderCardItem('撤销(次)', this.periodData.revoke)}
                        </div>
                    )}
                    {this.renderCard(
                        '一键续保',
                        () => this.onShow('showInsurancePlan'),
                        <div class="flex items-end">
                            {this.renderCardItem('减保(次)', this.periodData.automaticReduceInsur)}
                            <div class="flex-1">
                                <ElButton type="primary">一键续保</ElButton>
                            </div>
                        </div>
                    )}
                </ElRow>
                {/* 保险方案 */}
                <DrawerInsurancePlan
                    v-model:show={this.showInsurancePlan}
                    companyId={this.basicData.companyId}
                />
                {/* 加减保记录 */}
                <DrawerOperateRecord
                    v-model:show={this.showOperatorRecord}
                    companyId={this.basicData.companyId}
                />
            </div>
        )
    }
}

export default toNative<
    { basicData: PeriodInfoDto; companyBasicInfo: CompanyInfoDto },
    { refresh: () => void }
        >(BasicInfoView)
